package yongxin.controller.check;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;

import yongxin.entity.annealer.AnnealerEntity;
import yongxin.entity.check.ContractEntity;
import yongxin.entity.check.ContractProcutEntity;
import yongxin.entity.check.PayApplyBillEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.temp_record.TempRecordEntity;

/**   
 * @Title: Controller
 * @Description:  付款申请单 审批
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/payApplyCheckController")
public class PayApplyCheckController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PayApplyCheckController.class);

	@Autowired
	private SystemService systemService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 付款申请单列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "payApplyBillList")
	public ModelAndView processReport(HttpServletRequest request) {
		
		return new ModelAndView("yongxin/check/payApplyBillList");
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		        
				String sql = "	 select * from ";
				 sql += " OPENQUERY ( RemoteServer ,";
				 sql += " '";
				 sql += " SELECT ";
				 sql += " t_rp_PayApplyBill.FStatus  AS FStatus,t_rp_PayApplyBill.FBillID  AS FBillID,t_rp_PayApplyBill.FNumber  AS FBillNo,";
				 sql += " t_rp_PayApplyBill.FDate  AS FDate,t_currency.FName AS FBb, ";
				 sql += " case t_rp_PayApplyBill.FComboBox when 01 then ''往来款'' when 02 then ''购货款'' when 03 then ''预付款'' when 04 then ''工资预支'' else '''' end  AS FPayType," ;
				 sql += " t_ItemClass.FName AS  FCustomerType, ";
				 sql += " t_rp_PayApplyBill.FText AS FText," ;
				 sql += " t_Item.FName AS  FCustomerName,Convert(decimal(18,4),t_rp_PayApplyBillEntry.FApplyQuantity)  AS FApplyQuantity ,Convert(decimal(18,4),t_rp_PayApplyBillEntry.FApproveAmountFor) AS FApproveAmount, ";
				 sql += " t_rp_PayApplyBill.FExplanation  AS FExplanation,t_Department.FName AS FDepartmentName,t_Emp3.FName AS FEmployeeName, ";
				 sql += " t_User1.FName AS FCheckerMan,t_User.FName AS FBillMan,t_rp_PayApplyBill.FCheckDate AS FCheckDate ";
				 sql += " FROM  AIS2009.dbo.t_rp_PayApplyBill  t_rp_PayApplyBill INNER JOIN AIS2009.dbo.t_rp_PayApplyBillEntry t_rp_PayApplyBillEntry ON t_rp_PayApplyBill.FBillID=t_rp_PayApplyBillEntry.FBillID ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_ItemClass  t_ItemClass ON t_rp_PayApplyBill.FItemClassID=t_ItemClass.FItemClassID AND t_ItemClass.FItemClassID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_currency  t_currency ON t_rp_PayApplyBill.FCurrencyID=t_currency.FCurrencyID AND t_currency.FCurrencyID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_Item t_Item ON t_rp_PayApplyBill.FCustomer=t_Item.FItemID AND t_Item.FItemID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_User  t_User1 ON t_rp_PayApplyBill.FChecker=t_User1.FUserID AND t_User1.FUserID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_Department  t_Department ON t_rp_PayApplyBill.FDepartment=t_Department.FItemID AND t_Department.FItemID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_Emp t_Emp3 ON t_rp_PayApplyBill.FEmployee=t_Emp3.FItemID AND t_Emp3.FItemID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.t_User t_User ON t_rp_PayApplyBill.FPreparer=t_User.FUserID AND t_User.FUserID<>0 ";
				 sql += "  LEFT  JOIN AIS2009.dbo.ICClassType ICClassType ON ABS(t_rp_PayApplyBillEntry.FClassID_SRC)=ABS(ICClassType.FID) AND ICClassType.FID<>0 ";
				 sql += "  WHERE t_rp_PayApplyBill.FBillID in ";
				 sql += "   ( select fbillid from AIS2009.dbo.ICClassCheckStatus  where  fcurrentlevel=1 and FClassTypeID = 1000040) ";
				 sql += " ') ";
				
				List<Map<String, Object>> maplist = null;
				List<Map<String, Object>> allmaplist = null;

				try
				{

					allmaplist = systemService.findForJdbc(sql);
					maplist = systemService.findForJdbcParam(sql, dataGrid.getPage(), dataGrid.getRows());

				} catch (Exception ex)
				{

				}
		 
				dataGrid.setTotal(allmaplist.size());
				dataGrid.setResults(maplist);
				TagUtil.datagrid(response, dataGrid);
		
	}


	
	/**
	 * 付款申请单详情页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(HttpServletRequest req) {
		
			String FBillID = req.getParameter("FBillID");
			
			String sql = "	 select * from ";
			 sql += " OPENQUERY ( RemoteServer ,";
			 sql += " '";
			 sql += " SELECT ";
			 sql += " t_rp_PayApplyBill.FStatus  AS FStatus,t_rp_PayApplyBill.FBillID  AS FBillID,t_rp_PayApplyBill.FNumber  AS FBillNo,";
			 sql += " t_rp_PayApplyBill.FDate  AS FDate,t_currency.FName AS FBb,";
			 sql += " case t_rp_PayApplyBill.FComboBox when 01 then ''往来款'' when 02 then ''购货款'' when 03 then ''预付款'' when 04 then ''工资预支'' else '''' end  AS FPayType," ;
			 sql += " t_ItemClass.FName AS  FCustomerType,t_rp_PayApplyBill.FText AS FText,  ";
			 sql += " t_Item.FName AS  FCustomerName,Convert(decimal(18,4),t_rp_PayApplyBillEntry.FApplyQuantity)  AS FApplyQuantity ,Convert(decimal(18,4),t_rp_PayApplyBillEntry.FApproveAmountFor) AS FApproveAmount, ";
			 sql += " t_rp_PayApplyBill.FExplanation  AS FExplanation,t_Department.FName AS FDepartmentName,t_Emp3.FName AS FEmployeeName, ";
			 sql += " t_User1.FName AS FCheckerMan,t_User.FName AS FBillMan,t_rp_PayApplyBill.FCheckDate AS FCheckDate ";
			 sql += " FROM  AIS2009.dbo.t_rp_PayApplyBill  t_rp_PayApplyBill INNER JOIN AIS2009.dbo.t_rp_PayApplyBillEntry t_rp_PayApplyBillEntry ON t_rp_PayApplyBill.FBillID=t_rp_PayApplyBillEntry.FBillID ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_ItemClass  t_ItemClass ON t_rp_PayApplyBill.FItemClassID=t_ItemClass.FItemClassID AND t_ItemClass.FItemClassID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_currency  t_currency ON t_rp_PayApplyBill.FCurrencyID=t_currency.FCurrencyID AND t_currency.FCurrencyID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_Item t_Item ON t_rp_PayApplyBill.FCustomer=t_Item.FItemID AND t_Item.FItemID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_User  t_User1 ON t_rp_PayApplyBill.FChecker=t_User1.FUserID AND t_User1.FUserID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_Department  t_Department ON t_rp_PayApplyBill.FDepartment=t_Department.FItemID AND t_Department.FItemID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_Emp t_Emp3 ON t_rp_PayApplyBill.FEmployee=t_Emp3.FItemID AND t_Emp3.FItemID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.t_User t_User ON t_rp_PayApplyBill.FPreparer=t_User.FUserID AND t_User.FUserID<>0 ";
			 sql += "  LEFT  JOIN AIS2009.dbo.ICClassType ICClassType ON ABS(t_rp_PayApplyBillEntry.FClassID_SRC)=ABS(ICClassType.FID) AND ICClassType.FID<>0 ";
			 sql += "  WHERE t_rp_PayApplyBill.FBillID = %s ";
			 sql += " ') ";
				
		      sql=String.format(sql, FBillID);  
		      System.out.println(FBillID + "---" + sql);
				
			// 根据	FContractID  查询合同信息
				List<Map<String,Object>>  mapList= systemService.findForJdbc(sql);
				PayApplyBillEntity entity = new PayApplyBillEntity();
				for (int i=0;i<mapList.size();i++)
				{
				       Map  map=(Map)mapList.get(i);
				       entity.setfBillID((Integer)map.get("FBillID"));
				       entity.setfBillNo((String) map.get("FBillNo"));
				       entity.setFDate((Date) map.get("FDate"));
				       entity.setfBb((String) map.get("FBb"));
				       entity.setfPayType((String) map.get("FPayType"));
				       entity.setfText((String) map.get("FText"));
				       entity.setfCustomerType((String) map.get("FCustomerType"));
				       entity.setfCustomerName((String) map.get("FCustomerName"));
				       entity.setfApplyQuantity((BigDecimal ) map.get("FApplyQuantity"));
				       entity.setfApproveAmount((BigDecimal ) map.get("FApproveAmount"));
				       entity.setFexplanation((String) map.get("FExplanation"));
				       entity.setfDepartmentName((String) map.get("FDepartmentName"));
				       entity.setfEmployeeName((String) map.get("FEmployeeName"));
				       entity.setfBillMan((String) map.get("FBillMan"));
				}
				
				req.setAttribute("payApplyBillPage", entity);
			
			    return new ModelAndView("yongxin/check/payApplyBillDetail");
		
	}
	
	
	/**
	 * 审核
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "saveCheckIdea")
	@ResponseBody
	public AjaxJson saveCheckIdea(HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		String FBillNo = request.getParameter("no");
		String FBillID = request.getParameter("id");
		System.out.println(FBillNo +  "------------" + FBillID);
		
		String userId = "";
		//获取登录用户
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		if(user.getUserName().equals("yuanxl")){
			
			userId = "16446";
			
         }else if(user.getUserName().equals("songxb")){
			
			userId = "16465";
		}else{
			
			userId = "16501";
		}
		
		
	   String sql = " SET XACT_ABORT ON ; update RemoteServer.AIS2009.dbo.ICClassCheckStatus ";                         
		      sql += " set fcheckman2 = ?,fcheckidea2 = '',fcheckdate2 = GETDATE(),fcurrentLevel=fcurrentLevel + 2  ";
		      sql += " where fbillid = ? ";
	   
	  String sql2  = " SET XACT_ABORT ON ;update OPENQUERY(RemoteServer,'select fstatus,fchecker,FCheckDate,FBillID from AIS2009.dbo.t_rp_PayApplyBill') ";
	         sql2 += " set fstatus = 1,fchecker=?,FCheckDate= GETDATE() where FBillID = ? ";
	  
		String sql3 =  " SET XACT_ABORT ON ;insert RemoteServer.AIS2009.dbo.ICClassCheckRecords( ";
		       sql3 += " FClassTypeID,FPage,FBillID,FBillEntryID,FBillNo, FBillEntryIndex,FCheckLevel, ";
		       sql3 += " FCheckLevelTo,FMode,FCheckMan, FCheckIdea,FCheckDate,FDescriptions ) ";

               sql3 += " Values (1000040,1,?,0,?,0,1,2,0,?,'',GETDATE(),'审核')";
	                
              systemService.executeSql(sql,userId,FBillID);
              System.out.println("--------------------------");
              systemService.executeSql(sql2,userId,FBillID);
              System.out.println("--------------------------");
              systemService.executeSql(sql3,FBillID,FBillNo,userId);
              System.out.println("--------------------------");
              
		      message = "单据号" + FBillNo + "审批成功";
		
		j.setMsg(message);
		return j;
	}
	/**
	 * 审核
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "saveUnCheckIdea")
	@ResponseBody
	public AjaxJson saveUnCheckIdea(HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		String FBillNo = request.getParameter("no");
		String FBillID = request.getParameter("id");
		
		String userId = "";
		//获取登录用户
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		if(user.getUserName().equals("yuanxl")){
			
			userId = "16446";
			
		}else if(user.getUserName().equals("songxb")){
			
			userId = "16465";
		}else{
			
			userId = "16501";
		}
		
   String sql = " SET XACT_ABORT ON ; update RemoteServer.AIS2009.dbo.ICClassCheckStatus ";                         
	      sql += " set fcheckman1 = '0',fcheckidea1 = '',fcheckdate1 = null,fcheckman2 = '0',fcheckidea2 = '',fcheckdate2 = null,fcurrentLevel=0 ";
	      sql += " where fbillid = ?";
		  
	String sql2 =  " SET XACT_ABORT ON ;insert RemoteServer.AIS2009.dbo.ICClassCheckRecords( ";
	       sql2 += " FClassTypeID,FPage,FBillID,FBillEntryID,FBillNo, FBillEntryIndex,FCheckLevel, ";
	       sql2 += " FCheckLevelTo,FMode,FCheckMan, FCheckIdea,FCheckDate,FDescriptions ) ";
	       sql2 += " Values (1000040,1,?,0,?,0,-1,-1,2,?,'',GETDATE(),'驳回')"; 
	       
	      systemService.executeSql(sql,FBillID);
	      systemService.executeSql(sql2,FBillID,FBillNo,userId);
		   message = "驳回审批成功";
		
		j.setMsg(message);
		return j;
	}
}

